package com.free.picture.ecognition.xfyun;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.free.picture.ecognition.xfyun.sign.LfasrSignature;
import com.free.picture.ecognition.xfyun.utils.HttpUtil;
import com.google.gson.Gson;
import org.apache.commons.lang.StringEscapeUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.security.SignatureException;
import java.util.HashMap;


public class Ifasrdemo {
    private static final String HOST = "https://raasr.xfyun.cn";
    private static String AUDIO_FILE_PATH;
    private static final String appid = "13554187";
    private static final String keySecret = "9cd141d722642159e72cb9210641fc66";

    private static final Gson gson = new Gson();

    static {
        try {
            AUDIO_FILE_PATH = Ifasrdemo.class.getResource("/").toURI().getPath() + "/audio/【第02课】向甜品店里的女生学聊天.mp3";
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) throws Exception {
        String result = upload(new File(AUDIO_FILE_PATH));
        String jsonStr = StringEscapeUtils.unescapeJavaScript(result);
        String orderId = String.valueOf(JSONUtil.getByPath(JSONUtil.parse(jsonStr), "content.orderId"));
        getResult(orderId);
//        System.out.println("这是识别结果" + ":" + getResult(orderId));
    }

    public static String upload(File file) throws SignatureException, FileNotFoundException {
        HashMap<String, Object> map = new HashMap<>(16);
        String fileName = file.getName();
        long fileSize = file.length();
        map.put("appId", appid);
        map.put("fileSize", fileSize);
        map.put("fileName", fileName);
        map.put("duration", "200");
        LfasrSignature lfasrSignature = new LfasrSignature(appid, keySecret);
        map.put("signa", lfasrSignature.getSigna());
        map.put("ts", lfasrSignature.getTs());

        String paramString = HttpUtil.parseMapToPathParam(map);
        System.out.println("upload paramString:" + paramString);

        String url = HOST + "/v2/api/upload" + "?" + paramString;
        System.out.println("upload_url:" + url);
        String response = HttpUtil.iflyrecUpload(url, new FileInputStream(file));

//        System.out.println("upload response:" + response);
        return response;
    }

    public static String getResult(String orderId) throws SignatureException, InterruptedException, IOException {
        HashMap<String, Object> map = new HashMap<>(16);
        map.put("orderId", orderId);
        LfasrSignature lfasrSignature = new LfasrSignature(appid, keySecret);
        map.put("signa", lfasrSignature.getSigna());
        map.put("ts", lfasrSignature.getTs());
        map.put("appId", appid);
        map.put("resultType", "transfer,predict");
        String paramString = HttpUtil.parseMapToPathParam(map);
        String url = HOST + "/v2/api/getResult" + "?" + paramString;
        System.out.println("\nget_result_url:" + url);

        String response = HttpUtil.iflyrecGet(url);
            JsonParse jsonParse = gson.fromJson(response, JsonParse.class);
            if (jsonParse.content.orderInfo.status == 4 || jsonParse.content.orderInfo.status == -1) {
//                System.out.println("订单完成:" + response);
                return write(response).toString();
            } else {
                System.out.println("进行中...，状态为:" + jsonParse.content.orderInfo.status);
                //建议使用回调的方式查询结果，查询接口有请求频率限制
            }
        return null;
    }

    public static StringBuilder write(String resp) throws IOException {
        StringBuilder result = new StringBuilder();
        JSONUtil.parseObj(resp).getJSONObject("content").getJSONObject("orderResult").getJSONArray("lattice").forEach(json -> {
            JSONUtil.parseObj(json).getJSONObject("json_1best").getJSONObject("st").getJSONArray("rt").forEach(rtJson -> {
                JSONUtil.parseObj(rtJson).getJSONArray("ws").forEach(wsJson -> {
                    JSONArray cw = JSONUtil.parseObj(wsJson).getJSONArray("cw");
                    cw.forEach(cwJson -> {
                        System.out.print(JSONUtil.parseObj(cwJson).getStr("w"));
                        result.append(JSONUtil.parseObj(cwJson).getStr("w"));
                    });
                });
            });
        });
        return result;
    }

    class JsonParse {
        Content content;
    }

    class Content {
        OrderInfo orderInfo;
    }

    class OrderInfo {
        Integer status;
    }
}
